<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/2
 * Time: 14:51
 */

namespace Think;


class TKException
{
    /**
     * @return mixed
     * 获取微信公众号的access_token
     * 缓存7000s
     */
    public function getAccessTokenForWX()
    {
        $access_token = S("mp_public_access_token_191105");
        if (!empty($access_token)) {
            return $access_token;
        } else {
            $appId = C('WX_CONFIG_ERROR.APP_ID_MP');//公众号的appid
            $appSecret = C('WX_CONFIG_ERROR.APP_SECRET_MP');//公众号的appSecret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            $res = httpRequest($url, 'get');
            $return = json_decode($res, 1);
            S("mp_public_access_token_191105", $return['access_token'], 5000);
            return $return['access_token'];
        }
    }

    /**
     * 发送服务号模板消息
     * @param array $data ['openid','first','errorSystem','errorCode','time','remark','logId']
     */
    public function sendMpTemplateMessage($data)
    {
//        judy:oRQW2wkdCHQWky2bu06YRD2sux_Q
//        paul :oRQW2wpx3mdphM-QrOlKGyX9hHXE
//        Amily：oRQW2wumLPzuYqeObcZ8nA20D6QU
//        Rita：oRQW2wtyhnNQ0smpojvA3mKfTVYQ
//        Richard：oRQW2whDTOZTqdoaDDGZ3dl3f4Yw
//        客服号：oRQW2wgsjqCj04oXH9if3qLP-eLM
//        鲈鱼：oRQW2wtpCr8WYmHRqHcaHblaNJ28
//        layne：oRQW2wga98SrvLPhy3PP0UX0Rnwk
//        Allan：oRQW2wrPIZ_X4OLj_aTzdo15Lssw
//        Hellen：oRQW2wuG644lOfVtEeNkCfykRWaM
        if(C("ENVIRONMENT") != 'pro'){
            return;
        }
        $access_token = $this->getAccessTokenForWX();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
        $data = array(
            "touser" => $data['openid'],
            "template_id" => "koaqsSvRmreqcl_Pl-reFErlDGdz81PAz7sWeczXiiw",
            "url" => "https://activity.tongkuaikeji.com/index.php/CollectCard/Log/detail?logId=" . $data['logId'],
            "data" => array(
                'first' => array("value" => $data['first']),
                "keyword1" => array("value" => $data['errorSystem']),
                "keyword2" => array("value" => $data['errorCode']),
                "keyword3" => array("value" => $data['time']),
                "remark" => array("value" => $data['remark'])
            )
        );
        $data = json_encode($data);
        $res = httpRequest($url, "post", $data);
    }
}